package com.yolov8.steam;

import lombok.extern.slf4j.Slf4j;
import org.bytedeco.ffmpeg.global.avcodec;
import org.bytedeco.javacv.*;
import org.bytedeco.opencv.opencv_core.Mat;
import org.bytedeco.opencv.helper.opencv_core.*;

import java.util.concurrent.BlockingQueue;
@Slf4j
public class VideoPusher implements Runnable {

    private final String outputUrl;
    private final BlockingQueue<Mat> outputQueue;
    private final int width;
    private final int height;
    private volatile boolean running = true;

    public VideoPusher(String outputUrl, BlockingQueue<Mat> outputQueue, int width, int height) {
        this.outputUrl = outputUrl;
        this.outputQueue = outputQueue;
        this.width = width;
        this.height = height;
    }

    @Override
    public void run() {
        FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(outputUrl, width, height);
        recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264);
        recorder.setFormat("flv");
        recorder.setFrameRate(25);
        recorder.setVideoBitrate(2_000_000);

        OpenCVFrameConverter.ToMat converter = new OpenCVFrameConverter.ToMat();

        try {
            log.info("📡 准备开始推流到: " + outputUrl);
            recorder.start();
            log.info("📡 开始推流到: " + outputUrl);

            while (running) {
                Mat frameMat = outputQueue.take(); // 从队列取出处理后的图像
                Frame frame = converter.convert(frameMat);
                recorder.record(frame);
                log.info("推送队列大小: " + outputQueue.size());
            }

            recorder.stop();
            recorder.release();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void stop() {
        running = false;
    }
}

